package com.aloda.orangebank.controller;

import com.aloda.orangebank.pojo.ChangePwd;
import com.aloda.orangebank.pojo.Result;
import com.aloda.orangebank.pojo.User;
import com.aloda.orangebank.service.UserService;
import com.aloda.orangebank.utils.JwtUtils;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j//自动生成日志的注解
//@CrossOrigin
@RestController//controller层的注解
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @PostMapping("/register")//post请求的路径
    public Result register(@RequestBody User user) {
        log.info("注册的用户：{}", user);
        if (userService.register(user)){
            return Result.success("注册成功");
        }
        return Result.error("该用户名已注册");
    }

    @PostMapping ("/login")
    public Result login(@RequestBody User user){
        log.info("登录的用户：用户名{}，密码{}",user.getUsername(),user.getPassword());
        User u = userService.login(user);
        if(u!=null){
            Map<String,Object> claims =new HashMap<>();
            claims.put("id",u.getId());
            claims.put("username",u.getUsername());
            String jwt = JwtUtils.generateJwt(claims);//jwt包含了当前登录的员工信息
            return Result.success(jwt);
        }
        return Result.error("用户名或密码错误");
    }

    @GetMapping("/UserMsg01/{id}")
    public Result getUserMsg(@PathVariable Integer id){
        log.info("请求页面信息的用户id是：{}",id);
        User user =userService.getByUserId(id);
        return Result.success(user);
    }
    @PutMapping("/set")
    public Result setUserInfo(@RequestBody User user){
        log.info("更新的用户信息{}",user);
        int flag=userService.setUserInfo(user);
        if(flag==2){
            return Result.error("修改的用户名已注册！");
        }else if(flag==1){
            return Result.success("修改成功");
        }
        return Result.error("修改失败");
    }
    @PutMapping("/changePass")
    public Result setUserPwd(@RequestBody ChangePwd changePwd){
        log.info("修改密码的用户:{}",changePwd);
        int flag = userService.setUserPwd(changePwd);
        if(flag==0){
            return Result.error("密码未更改！");
        }else if (flag==1){
            log.info("flag={}",flag);
            return Result.error("旧密码不正确！");

        }
        return Result.success("修改成功");
    }
}
